#include "head.h"

int log_file_fd;

pthread_mutex_t log_mutex;

//初始化日志
int init_log(const char * log_path) {
    log_file_fd = open(log_path,O_RDWR | O_CREAT | O_APPEND ,0664);
    if(log_file_fd == -1) {
        fprintf(stderr,"error : on 24 line of log.c -- %s \n",strerror(errno));
        perror("Failed to open *.log");
        return 0;
    }
    return 1;
}   

//获取当前时间
void get_current_time(char* buf,ssize_t len) {
    time_t now;
    time(&now);
    struct tm *time_info = localtime(&now);
    strftime(buf,len,"%Y-%m-%d %H:%M:%S",time_info);
}


//关闭日志文件
void close_log() {
    if(log_file_fd){
       close(log_file_fd);
    } 
}

void write_log(LOG_LEVEL level,const char * str,const char *file_name,const char *func,int line) {
    
    if( level < DEFAULT_LEVEL ) 
        return;
    pthread_mutex_lock(&log_mutex);

    //记录错误位置
    char error_location[64];
    memset(error_location,0,sizeof(error_location));
    sprintf(error_location,"In the %s,the %s,line %d",file_name,func,line); 
    

    //存储打印日志时的时间信息
    char time_info[32];
    bzero(time_info,sizeof(time_info));
    get_current_time(time_info,sizeof(time_info));
    
    //获取当前用户
    uid_t uid = getuid();
    struct passwd * user_info;
    user_info = getpwuid(uid);

    //将枚举类型的日志等级转换成字符串
    char log_level[10];
    memset(log_level,0,sizeof(log_level));
    switch(level) {
        case INFO : strcpy(log_level,"INFO");
                    break;
        case WARING: strcpy(log_level,"WARING");
                     break;
        case ERROR: strcpy(log_level,"ERROR");
                    break;
    }
    
    //将所有信息汇总，然后一次写入到.log文件
    char log_message[1024];
    bzero(log_message,sizeof(log_message));
    sprintf(log_message,"%s %s %s (%s): %s",time_info,user_info -> pw_name,log_level,error_location,str);

    //写入到log文件
    write(log_file_fd,log_message,strlen(log_message));
    
    //close_log(log_file_fd);


    pthread_mutex_unlock(&log_mutex);
}
